package com.subframe7536.sa.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.service.base.ResponseResult;
import com.subframe7536.sa.entity.LoginEntity;
import com.subframe7536.sa.entity.MyUserdetailEntity;
import org.example.service.VO.PhoneLoginVO;
import com.subframe7536.sa.mapper.LoginMapper;
import org.example.service.LoginService;
import com.subframe7536.sa.utils.JwtUtil;
import com.subframe7536.sa.utils.RedisCacheUtil;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author subframe7536
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, LoginEntity> implements LoginService {

    @Resource
    private AuthenticationManager manager;

    @Resource
    private LoginMapper loginMapper;

    @Resource
    private RedisCacheUtil redis;

    @Resource
    private ThreadPoolTaskExecutor executor;

    @Override
    public ResponseResult<String> login(PhoneLoginVO one) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(one.getPhone(), one.getPassword());
        Authentication authentication = manager.authenticate(token);
        if (authentication == null) {
            throw new RuntimeException("没有该用户");
        }
        MyUserdetailEntity user = (MyUserdetailEntity) authentication.getPrincipal();
        String phone = user.getUser().getPhone();
        String jwt = JwtUtil.createJWT(phone);
        executor.execute(() -> loginMapper.login(phone, LocalDateTime.now()));
        redis.set("login" + user.getUser().getPhone(), user);
        return ResponseResult.ok(jwt, "登录成功");
    }

    @Override
    public ResponseResult<String> logout(String token) {
        String phone = null;
        try {
            phone = JwtUtil.parseJWT(token).getSubject();
            //删除redis中的值
        } catch (Exception e) {
            // TODO: 2022/3/6 throw illegalTokenException
            e.printStackTrace();
        }
        Boolean del = redis.del("login" + phone);
        if (!del) {
            return ResponseResult.failed("退出失败");
        }
        return ResponseResult.ok(null, "退出成功");
    }

}
